<template>
  <el-cascader
      ref="selectDeptUser"
      style="width: 100%"
      v-model="selectedValues"
      :options="treeData"
      :props="treeProps"
      :show-all-levels="false"
      filterable
      :disabled="disabled"
      clearable
      @change="handleChange"
  />
</template>

<script lang="ts">
import {defineComponent, onMounted, PropType, ref, watch} from 'vue'
import {ProductCategoryApi} from '@/api/factory/product/category'

// 定义级联选择器选项的类型
interface CascaderOption {
  id: string | number
  name: string
  children?: CascaderOption[]
}

// 定义TreeProps的类型
interface TreeProps {
  value: string
  label: string
  emitPath: boolean
  multiple: boolean
  checkStrictly: boolean
}

// 定义ResultProps的类型
interface ResultProps {
  name: string
  id: string
}

export default defineComponent({
  name: 'CascaderFactoryCategory',
  props: {
    options: {
      type: Object as PropType<Partial<TreeProps>>,
      default: () => ({})
    },
    value: {
      type: [Array, String] as PropType<string[] | string | number[] | number>,
      default: () => []
    },
    resultProps: {
      type: Object as PropType<Partial<ResultProps>>,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  setup(props, {emit}) {
    // 响应式变量
    const treeData = ref<CascaderOption[]>([])
    const selectedValues = ref<typeof props.value>(props.value)
    const selectDeptUser = ref<HTMLElement | null>(null)

    // 初始属性
    const treeProps = ref<TreeProps>({
      value: 'id',
      label: 'name',
      emitPath: false,
      multiple: false,
      checkStrictly: true
    })

    const resultPropsValue = ref<ResultProps>({
      name: 'name',
      id: 'id'
    })

    // 初始化方法
    const init = async () => {
      // 合并属性
      Object.assign(resultPropsValue.value, props.resultProps)
      Object.assign(treeProps.value, props.options)
      try {
        treeData.value = await ProductCategoryApi.getProductCategoryTreeList()
      } catch (error) {
        treeData.value = []
      }

    }

    // 处理选择变化
    const handleChange = (value: any) => {
      emit('change', value)
    }

    // 监听value变化
    watch(
        () => props.value,
        (newVal) => {
          selectedValues.value = newVal
        }
    )

    // 监听selectedValues变化
    watch(
        selectedValues,
        (newVal) => {
          emit('input', newVal)
        }
    )

    // 组件挂载时初始化
    onMounted(() => {
      init()
    })

    return {
      treeData,
      selectedValues,
      treeProps,
      resultPropsValue,
      selectDeptUser,
      init,
      handleChange
    }
  }
})
</script>

<style scoped>

</style>
